package controllers;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;

import models.cms.*;
import org.apache.commons.codec.digest.Md5Crypt;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;

import models.cms.Resource.ResourceType;
import models.sys.User;
import org.jsoup.Jsoup;
import play.Logger;
import play.data.Upload;
import play.mvc.With;
import ret.Ret;
import utils.NeedLogin;
import utils.ResourceUtils;
import utils.SessionUtils;
import utils.TagUtils;

@With(LoginFilter.class)
public class B extends SController {

    public static void register(String mobile, String passwd, String nickname, String valcode) {
        User user = null;
        if ((user = User.findByMobile(mobile)) == null) {
            renderJSON(Ret.error("手机号码不存在"));
            return;
        }
        if (StringUtils.isEmpty(passwd) || passwd.length() < 8) {
            renderJSON(Ret.error("密码长度不够8位"));
            return;
        }
        if (!StringUtils.equals(user.validateCode, valcode) || user.validateExpr.before(new Date())) {
            renderJSON(Ret.error("验证码不对或者验证码已经过期"));
            return;
        }
        user.validateCode = null;
        user.validateExpr = null;
        if (StringUtils.isNotEmpty(nickname)) {
            user.nickname = nickname;
        }
        user.salt = RandomStringUtils.random(20, "abcdefghijklmnopqrstuvwxyz");
        user.passwd = Md5Crypt.apr1Crypt(passwd, user.salt);
        user.save();
        renderJSON(Ret.redirect("/"));
    }

    public static void login(String mobile, String passwd) {
        User user = User.findByMobile(mobile);
        if (user != null && StringUtils.equals(user.passwd, Md5Crypt.apr1Crypt(passwd, user.salt))) {
            SessionUtils.setCurrentUser(user);
            renderJSON(Ret.redirect("/"));
        }
        renderJSON(Ret.error("登录失败"));
    }

    public static void validateMobileForNewUser(String mobile) {
        if (StringUtils.isEmpty(mobile) || mobile.length() != 11) {
            renderJSON(Ret.error("手机号码不正确"));
            return;
        }
        User user = null;
        if ((user = User.findByMobile(mobile)) == null) {
            user = new User();
            user.mobile = mobile;
        } else {
            renderJSON(Ret.error("手机号码已经注册"));
        }
        user.validateCode = "1234";// RandomStringUtils.random(4,
        // "0123456789");
        user.validateExpr = DateUtils.addMinutes(new Date(), 15);
        Logger.info("mobile:%s,validate_code:%s", mobile, user.validateCode);
        user.save();
        renderJSON(Ret.ok("请查收验证码"));
    }

    @NeedLogin
    public static void updateUserMemo(String memo) {
        User currentUser = SessionUtils.getCurrentUser();
        currentUser.memo = memo;
        currentUser.save();
        renderJSON(Ret.ok());
    }

    @NeedLogin
    public static void post(String subject, String author, String tags, String summary, String content,
                            Upload[] files) {
        Post post = new Post();
        post.subject = subject;
        post.author = author;
        post.tags_text = tags;
        post.summary = summary;
        post.content = content;
        post.tags = TagUtils.text_to_tags(post.tags_text);
        if(post.tags.size() == 0) {
            renderJSON(Ret.error("至少需要一个标签"));
        }
        if (StringUtils.isEmpty(post.summary)) {
            String text = Jsoup.parse(post.content).text();
            post.summary = text.substring(0, Math.min(50, text.length()));
        }
        post.created_at = new Date();
        post.resources = new ArrayList<Resource>();
        if (files != null && files.length > 0) {
            final Post finalP = post;
            Arrays.stream(files).forEach(sid -> {
                finalP.resources.add(ResourceUtils.process(sid));
            });
        }
        post.images = "";
        if (post.resources.size() > 0) {
            for (Resource r : post.resources) {
                if (r.type == ResourceType.IMAGE) {
                    post.images += r.hash + ",";
                    break;
                }
            }
        }
        post.user = SessionUtils.getCurrentUser();
        post.save();
        renderJSON(Ret.redirect("/view_post/" + post.id));
    }

    @NeedLogin
    public static void reply(long id, long post_id, String content, Upload[] files) {
        Post post = Post.findById(post_id);
        if (post == null) {
            renderJSON(Ret.error("要回复的帖子已经不存在"));
        }
        Post reply = id > 0 ? Post.findById(id) : new Post();
        reply.to_post = post;
        reply.content = content;
        reply.user = SessionUtils.getCurrentUser();
        reply.created_at = new Date();
        if (files != null && files.length > 0) {
            reply.resources = new ArrayList<Resource>();
            Arrays.stream(files).forEach(rid -> {
                reply.resources.add(ResourceUtils.process(rid));
            });
        }
        reply.save();
        post.cnt_reply = post.cnt_reply + 1;
        post.save();
        renderJSON(Ret.redirect("/view_post/" + post.id));
    }

    @NeedLogin
    public static void comment(long to_post, long to_comment, String content) {
        if (StringUtils.isEmpty(content)) {
            renderJSON(Ret.error("评论不能为空"));
        }
        Post post = Post.findById(to_post);
        if (post == null) {
            renderJSON(Ret.error("要回复的帖子已经不存在"));
        }
        Comment comment = new Comment();
        comment.content = content;
        comment.to_post = post;
        comment.to_comment = Comment.findById(to_comment);
        comment.created_at = new Date();
        comment.user = SessionUtils.getCurrentUser();
        comment.save();

        renderJSON(Ret.redirect("/view_post/" + (comment.to_post.to_post != null ? comment.to_post.to_post.id : comment.to_post.id)));
    }

    @NeedLogin
    public static void favor(long post_id) {
        Post post = Post.findById(post_id);
        PostUserState postUserState = post.load_user_state(SessionUtils.getCurrentUser());
        postUserState.favor = !postUserState.favor;
        postUserState.save();
        post.cnt_favorite += postUserState.favor ? 1 : -1;
        post.save();
        renderJSON(Ret.ok().data("state", postUserState));
    }

    @NeedLogin
    public static void follow(long post_id) {
        Post post = Post.findById(post_id);
        PostUserState postUserState = post.load_user_state(SessionUtils.getCurrentUser());
        postUserState.follow = !postUserState.follow;
        postUserState.save();
        renderJSON(Ret.ok().data("state", postUserState));
    }

    @NeedLogin
    public static void voteup(long post_id) {
        Post post = Post.findById(post_id);
        PostUserState postUserState = post.load_user_state(SessionUtils.getCurrentUser());
        postUserState.voteup = !postUserState.voteup;
        postUserState.save();
        post.cnt_voteup += postUserState.voteup ? 1 : -1;
        post.save();
        renderJSON(Ret.ok().data("state", postUserState));
    }

    @NeedLogin
    public static void new_tag(long post_id, String tagname) {
        Post post = Post.findById(post_id);
        post.tags.addAll(TagUtils.text_to_tags(tagname));
        post.tags_text = TagUtils.tags_to_text(post.tags);
        post.save();
        renderJSON(Ret.ok().data("post", post));
    }

}
